<?php

namespace App\Http\Controllers\Admin;

use App\Http\Config\ErrorCode;
use App\Library\TcScfUtil;
use App\Library\UpTools;
use App\Models\Admin\AdminUser;
use App\Models\Admin\Configs;
use App\Models\Admin\Orders;
use App\Models\Admin\TcAuther;
use App\Models\Admin\TcSale;
use App\Models\Admin\TencentOrder;
use App\Models\Admin\TencentStatistics;
use App\Models\Admin\TencentTemp;
use App\Models\Admin\TencentTransfer;
use App\Models\Admin\WalletLogs;
use App\Models\Member\MemberBase;
use App\Models\video\CommonServer;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
//捕获错误信息
use TencentCloud\Common\Exception\TencentCloudSDKException;
//参数
use TencentCloud\Common\Credential;
// 导入可选配置类
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Partners\V20180321\Models\DescribeAgentBillsRequest;
use TencentCloud\Partners\V20180321\Models\ModifyClientRemarkRequest;
//审核客户
use TencentCloud\Partners\V20180321\Models\AuditApplyClientRequest;
//代理商返佣信息
use TencentCloud\Partners\V20180321\Models\DescribeRebateInfosRequest;
//查询客户余额
use TencentCloud\Partners\V20180321\Models\DescribeClientBalanceRequest;

use TencentCloud\Partners\V20180321\PartnersClient;

class TencentController extends BaseController{

    public function __construct(Request $request){
        parent::__construct($request);
    }

    //业务明细
    public function index(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
		 require_once  base_path().'/vendor/tencentcloud-sdk-php/TCloudAutoLoader.php';
        $con = Configs::query()->where("mall_id", $request->mallData["id"])->first();
        $cred = new Credential($con->tencent_secretid, $con->tencent_secrekey);
        $httpProfile = new HttpProfile();
        $httpProfile->setEndpoint("partners.tencentcloudapi.com");
        $clientProfile = new ClientProfile();
        $clientProfile->setHttpProfile($httpProfile);
        $client = new PartnersClient($cred, "", $clientProfile);
        $req = new DescribeAgentBillsRequest();

        $page_size = $request->input('page_size', 10);
        $page_no = $request->input('page_no', 1);
        $req->SettleMonth = $request->input('settle_month', 1);
        $req->Offset = $page_no-1;
        $req->Limit = $page_size;
        $resp = $client->DescribeAgentBills($req);
        $res = $resp->toJsonString();
        $res = json_decode($res,true);
        if (is_array($res['AgentBillSet'])){
            $data['code'] = 0;
            $data['msg'] = '请求成功';
            $data['data']['list'] = $res['AgentBillSet'];
            $data['data']['total'] = 0;
            return $this->return_result($data);
        }else{
            $this->returnData['code'] = 1;
            $this->returnData['msg'] = '请求失败';
            return $this->return_result($this->returnData);
        }
    }

    public $defaultSale = [
        ["sales_name" => "未指派", "sales_uin" => "0000", "uin" => "0000"],
        ["SalesName" => "未指派", "SalesUin" => "0000", "Uin" => "0000"]
    ];

    public function getSaleByUser(Request $request){
        $fun = function (){
            $con = Configs::query()->where("mall_id", request()->mallData["id"])->first();
            if (!$con->tencent_secretid || !$con->tencent_secrekey){
                throw new \Exception("腾讯云参数未配置");
            }
            $params = [
                "OrderDirection" => "DESC", "Offset" => 0, "Limit" => 1000
            ];
            $res = TcScfUtil::getInstance($con->tencent_secretid, $con->tencent_secrekey, 'partner')->describeSalesmans($params);
            $data = [];
            if(!empty($res["data"])){
                foreach ($res['data']['AgentSalesmanSet'] as $item){
                    $data[] = ["sales_name" => $item["SalesName"], "sales_uin" => $item["SalesUin"]];
                }
            }
            $data[] = $this->defaultSale[0];
            return $data;
        };
        if($this->AU["position"] == "超级管理员") {
            $this->returnData["data"] = $fun();
            return $this->returnData;
        }else{
            $tt = DB::table('permissions as p')
                ->leftJoin('admin_permission_role as pr', 'pr.permission_id', '=', 'p.id')
                ->leftJoin('admin_role_user as ru', 'ru.role_id', '=', 'pr.role_id')
                ->where("ru.user_id", $this->AU["id"])
                ->where("p.name", "admin.tencent.checkAllCustomer")
                ->count();
            if ($tt) {
                $this->returnData["data"] = $fun();
                return $this->returnData;
            }
        }
        $sdf = TcAuther::query()->where(["mall_id" => $request->mallData["id"], "admin_id" => $this->AU["id"]])->select("id")->with("sale_list")->first();
        if(!empty($sdf["sale_list"])) {
            $this->returnData["data"] = $sdf["sale_list"];
        }else{
            $this->returnData["data"] = [];
        }
        return $this->returnData;
    }

    //已审核客户列表
    public function customer_examine(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $con = Configs::query()->where("mall_id", $request->mallData["id"])->first();
        if (!$con->tencent_secretid || !$con->tencent_secrekey){
            return $this->return_result(ErrorCode::code("customized", "腾讯云参数未配置"));
        }
        $page_size = $request->input('page_size', 50);
        $page_no = $request->input('page_no', 1);
        $arrears = $request->input('arrears', '');
        $client_type = $request->input('client_type', '');
        $project_type = $request->input('project_type', '');
        $client_uin = $request->input('client_uin', '');
        $client_name= $request->input('client_name', '');
        $client_remark= $request->input('client_remark', '');
        $sortName= $request->input('sortName', '');
        $sortOrder= $request->input('sortOrder', '');
        $sales_name= $request->input('sales_name', '');

        $requestParams = ["OrderDirection" => "DESC", 'Offset' => $page_no - 1, "Limit" => $page_size];
        $requestParams["Offset"] = $requestParams["Offset"] * $requestParams["Limit"];
        if ($arrears){
            $requestParams['HasOverdueBill'] = $arrears;
        }
        if ($client_type){
            $requestParams['ClientType'] = $client_type;
        }
        if ($project_type){
            $requestParams['ProjectType'] = $project_type;
        }
        if ($client_uin){
            $requestParams['ClientUin'] = $client_uin;
        }
        if ($client_name){
            $requestParams['ClientName'] = $client_name;
        }
        if ($client_remark){
            $requestParams['ClientRemark'] = $client_remark;
        }
        if ($sales_name){
            $requestParams['SalesName'] = $sales_name;
        }
        if ($request->sales_uin){
            $requestParams['SalesUin'] = $request->sales_uin;
        }
        if($sortName == "AgentTime" && $sortOrder == 'asc'){
            $requestParams["OrderDirection"] = 'ASC';
        }
        $res = TcScfUtil::getInstance($con->tencent_secretid, $con->tencent_secrekey, "partner")->describeAgentAuditedClients($requestParams);
        if (!empty($res['data'])){
            $this->returnData['data'] = ["list" => $res['data']['AgentClientSet'], "total" => $res['data']['TotalCount']];
            if ($sortName && $sortName = "ThisMonthAmt"){
                //根据字段last_name对数组$data进行降序排列
                $last_names = array_column($this->returnData['data']['list'],'ThisMonthAmt');
                if ($sortOrder && $sortOrder = "desc"){
                    array_multisort($last_names,SORT_DESC, $this->returnData['data']['list']);
                }else{
                    array_multisort($last_names,SORT_ASC,$this->returnData['data']['list']);
                }
            }else if($sortName && $sortName = "LastMonthAmt"){
                $last_names = array_column($this->returnData['data']['list'],'LastMonthAmt');
                if ($sortOrder && $sortOrder = "desc"){
                    array_multisort($last_names,SORT_DESC,$this->returnData['data']['list']);
                }else{
                    array_multisort($last_names,SORT_ASC,$this->returnData['data']['list']);
                }
            }
        }else{
            $this->returnData['code'] = 1;
            $this->returnData['msg'] = '请求失败';
        }
        return $this->return_result($this->returnData);
    }

    public function getCustomerInfo(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        if(!$request->clientUin){
            return ErrorCode::code("params_not_exist", "客户ID");
        }
        $con = Configs::query()->where("mall_id", $request->mallData["id"])->first();
        if (!$con->tencent_secretid || !$con->tencent_secrekey){
            $data['code'] = 1;
            $data['msg'] = '腾讯云参数未配置';
            $data['data'] = '';
            return $this->return_result($data);
        }
        $client = TcScfUtil::getInstance($con->tencent_secretid, $con->tencent_secrekey, "partner");
        $result = $client->describeClientBalance(['ClientUin' => $request->clientUin]);
        $this->returnData['data'] = ['balance' => isset($result['data']['Balance']) ? $result['data']['Balance'] / 100 : 0];
        $result = $client->describeAgentClientGrade($request->clientUin);
        $this->returnData['data'] = array_merge($this->returnData['data'], ['grade' => !empty($result['data']['ClientGrade']) ? $result['data']['ClientGrade'] : '-']);
        return $this->return_result($this->returnData);
    }

    //待审核客户列表
    public function customer_be_audited(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $con = Configs::query()->where("mall_id", $request->mallData["id"])->first();
        if (!$con->tencent_secretid || !$con->tencent_secrekey){
            return $this->return_result(ErrorCode::code("customized", "腾讯云参数未配置"));
        }
        $requestParams = ["OrderDirection" => "DESC", 'Offset' => $request->page_no ? $request->page_no - 1 : 0, "Limit" => $request->page_size ?: 50];
        if($request->sortName == "AgentTime" && $request->sortOrder == 'asc'){
            $requestParams["OrderDirection"] = 'ASC';
        }
        if ($request->sales_uin){
            $requestParams['SalesUin'] = $request->sales_uin;
        }
        if ($request->sales_name){
            $requestParams['SalesName'] = $request->sales_name;
        }
        $requestParams["Offset"] = $requestParams["Offset"] * $requestParams["Limit"];
        $res = TcScfUtil::getInstance($con->tencent_secretid, $con->tencent_secrekey, "partner")->describeAgentClients($requestParams);
        if (is_array($res['data']['AgentClientSet'])){
            $this->returnData['data'] = ["list" => $res['data']['AgentClientSet'], "total" => $res['data']['TotalCount']];
        }else{
            $this->returnData['code'] = 1;
            $this->returnData['msg'] = '请求失败';
        }
        return $this->return_result($this->returnData);
    }

    // 转账
    public function getAgentTransferMoney(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        if (!$request->clientUin){
            return $this->return_result(ErrorCode::code("params_not_exist", "	客户账号ID"));
        }
        if (!$request->amount){
            return $this->return_result(ErrorCode::code("params_not_exist", "	转账金额"));
        }
        try {
            if (Cache::has("{$request->mallData["id"]}_{$this->AU["id"]}_tc_transfer")) {
                return $this->return_result($this->returnData);
            }
            Cache::put("{$request->mallData["id"]}_{$this->AU["id"]}_tc_transfer", 1, 1);
            if ($this->AU["position"] != "超级管理员") {
                $transfer_quota = TcAuther::query()->where(["admin_id" => $this->AU["id"]])->value("transfer_quota");
                $transfer_quota = $transfer_quota ?: 0;
                $total = TencentTransfer::query()->where(["user_id" => $this->AU["id"]])->sum("money");
                if ($total + $request->amount > $transfer_quota) {
                    return $this->return_result(ErrorCode::code("customized", "已超过可转账限额了"));
                }
            }
            $con = Configs::query()->where("mall_id", $request->mallData["id"])->first();
            $requestParams = ["ClientUin" => $request->clientUin, 'Amount' => $request->amount * 100];
            $this->returnData = TcScfUtil::getInstance($con->tencent_secretid, $con->tencent_secrekey, "partner")->agentTransferMoney($requestParams);
            if ($this->returnData["code"] == '0') {
                try {
                    TencentTransfer::query()->insert([
                        "mall_id" => $request->mallData["id"], "user_id" => $this->AU["id"], "customer" => $requestParams["ClientUin"],
                        "money" => $request->amount, "create_time" => Carbon::now()->toDateTimeString()
                    ]);
                    Cache::forget("{$request->mallData["id"]}_{$this->AU["id"]}_tc_transfer");
                }catch (\Exception $e){
                    $this->returnData["msg"] = "转账成功，但后续操作失败";
                }
            } else {
                if (strpos($this->returnData["msg"], "call interface error") !== false) {
                    $this->returnData["msg"] = "余额不够";
                }
            }
        }catch (\Exception $e){
            $this->returnData = ErrorCode::code("customized", $e->getMessage());
        }
        return $this->return_result($this->returnData);
    }

    public function getAccountBalance(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $con = Configs::query()->where("mall_id", $request->mallData["id"])->first();
        $res = TcScfUtil::getInstance($con->tencent_secretid, $con->tencent_secrekey)->describeAccountBalance();
        if($res["code"] == "0"){
            $data = ["balance" => $res["data"]["Balance"] / 100, "result" => "获取成功"];
        }else{
            $data = ["balance" => 0, "result" => $res["msg"]];
        }
        $this->returnData["data"] = $data;
        return $this->return_result($this->returnData);
    }

    // 业务员查询接口
    public function getDescribeSalesmans(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        // 实例化一个证书对象，入参需要传入腾讯云账户secretId，secretKey
        $con = Configs::query()->where("mall_id", $request->mallData["id"])->first();
        if (!$con->tencent_secretid || !$con->tencent_secrekey){
            $data['code'] = 1;
            $data['msg'] = '腾讯云参数未配置';
            $data['data'] = '';
            return $this->return_result($data);
        }
        $page_size = $request->input('page_size', 10);
        $page_no = $request->input('page_no', 1);
        $params = [
            "OrderDirection" => "DESC", "Offset" => $page_no -1, "Limit" => $page_size
        ];
        $params["Offset"] = $params["Offset"] * $params["Limit"];
        if($request->salesName){
            $params["SalesName"] = $request->salesName;
        }
        $res = TcScfUtil::getInstance($con->tencent_secretid, $con->tencent_secrekey, 'partner')->describeSalesmans($params);
        if (!empty($res['data'])){
            $res['data']['AgentSalesmanSet'][] = $this->defaultSale[1];
            $data['code'] = 0;
            $data['msg'] = '请求成功';
            $data['data']['rows'] = $res['data']['AgentSalesmanSet'];
            $data['data']['total']= $res['data']['TotalCount'];
            return $this->return_result($data);
        }else{
            $this->returnData['code'] = 1;
            $this->returnData['msg'] = isset($res["msg"]) ? $res["msg"] : '请求失败';
            return $this->return_result($this->returnData);
        }
    }

    // 修改客户备注
    public function modifyClientRemark(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        require_once  base_path().'/vendor/tencentcloud-sdk-php/TCloudAutoLoader.php';
        // 实例化一个证书对象，入参需要传入腾讯云账户secretId，secretKey
        $con = Configs::query()->where("mall_id", $request->mallData["id"])->first();
        if (!$con->tencent_secretid || !$con->tencent_secrekey){
            $data['code'] = 1;
            $data['msg'] = '腾讯云参数未配置';
            $data['data'] = '';
            return $this->return_result($data);
        }
        if(!$request->clientUin){
            return ErrorCode::code("params_not_exist", "账号ID");
        }
        if(!$request->remark){
            return ErrorCode::code("params_not_exist", "备注");
        }
        $cred = new Credential($con->tencent_secretid, $con->tencent_secrekey);
        $httpProfile = new HttpProfile();
        $httpProfile->setEndpoint("partners.tencentcloudapi.com");
        $clientProfile = new ClientProfile();
        $clientProfile->setHttpProfile($httpProfile);
        $client = new PartnersClient($cred, "", $clientProfile);
        $req = new ModifyClientRemarkRequest();
        $req->ClientUin = $request->clientUin;
        $req->ClientRemark = $request->remark;
        $resp = $client->ModifyClientRemark($req);
        $res = $resp->toJsonString();
        $res = json_decode($res,true);
        $data['code'] = 0;
        $data['msg'] = '请求成功';
        return $this->return_result($data);
    }

    //审核客户
    public function examine_customer(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        require_once  base_path().'/vendor/tencentcloud-sdk-php/TCloudAutoLoader.php';
        $con = Configs::query()->where("mall_id", $request->mallData["id"])->first();
        if (!$con->tencent_secretid || !$con->tencent_secrekey){
            $data['code'] = 1;
            $data['msg'] = '腾讯云参数未配置';
            $data['data'] = '';
            return $this->return_result($data);
        }
        try {
            $cred = new Credential($con->tencent_secretid, $con->tencent_secrekey);
            $httpProfile = new HttpProfile();
            $httpProfile->setEndpoint("partners.tencentcloudapi.com");

            $clientProfile = new ClientProfile();
            $clientProfile->setHttpProfile($httpProfile);
            $client = new PartnersClient($cred, "", $clientProfile);

            $ClientUin = $request->input('ClientUin','');
            $Note = $request->input('Note','');
            $req = new AuditApplyClientRequest();
            $req->ClientUin = $ClientUin;
            $req->AuditResult = 'accept';   //同意
            $req->Note = $Note; //申请理由      B类客户审核时必须填写申请理由 有腾讯云审核

            $resp = $client->AuditApplyClient($req);

            $resp->toJsonString();
        } catch(TencentCloudSDKException $e) {
            $data['code'] = 1;
            $data['msg'] = $e->getMessage();
            $data['data'] = '';
            return $this->return_result($data);
        }
        $data['code'] = 0;
        $data['msg'] = '请求成功';
        $data['data'] = '';
        return $this->return_result($data);
    }

    //修改客户备注
    public function update_customer_remarks(Request $request){
        $con = Configs::query()->where("mall_id", $request->mallData["id"])->first();
        $cred = new Credential($con->tencent_secretid, $con->tencent_secrekey);
        $httpProfile = new HttpProfile();
        $httpProfile->setEndpoint("partners.tencentcloudapi.com");
        $clientProfile = new ClientProfile();
        $clientProfile->setHttpProfile($httpProfile);
        $client = new PartnersClient($cred, "", $clientProfile);
        $req = new ModifyClientRemarkRequest();
        $req->ClientUin = "";//客户账号ID
        $req->ClientRemark = "";//客户备注名称
        $resp = $client->ModifyClientRemark($req);

        print_r($resp->toJsonString());
    }

    //查询余额
    public function select_balance(Request $request){
        $con = Configs::query()->where("mall_id", $request->mallData["id"])->first();
        $cred = new Credential($con->tencent_secretid, $con->tencent_secrekey);
        $httpProfile = new HttpProfile();
        $httpProfile->setEndpoint("partners.tencentcloudapi.com");

        $clientProfile = new ClientProfile();
        $clientProfile->setHttpProfile($httpProfile);
        $client = new PartnersClient($cred, "", $clientProfile);
        $req = new DescribeClientBalanceRequest();
        $req->ClientUin = ""; //客户Uid
        $resp = $client->DescribeClientBalance($req);

        print_r($resp->toJsonString());
    }

    //代付
    public function substitute_payment(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $con = Configs::query()->where("mall_id", $request->mallData["id"])->first();
        if (!$con->tencent_secretid || !$con->tencent_secrekey){
            return $this->return_result(ErrorCode::code("customized", "腾讯云参数未配置"));
        }
        $listData = $request->params ? (array)@json_decode($request->params, true) : [];
        if(empty($listData)){
            $listData = [['total_price' => $request->total_price, 'owner_uin' => $request->owner_uin, 'deal_name' => $request->deal_name]];
        }
        //获取用户折扣信息
        $user_discount = TcAuther::query()->where('admin_id',$this->AU["id"])->select('quota','old_quota','assign_quota')->first();
        $user_discount = json_decode(json_encode($user_discount),true);
        DB::beginTransaction();
        try{
            foreach ($listData as $k => $item) {
                $item['total_price'] = $item['total_price'] / 100;
                $lists = [$item['deal_name']];
                $res = TcScfUtil::getInstance($con->tencent_secretid, $con->tencent_secrekey, 'partner')->describeAgentPayDeals([
                    "Offset" => 0, "Limit" => 100, "Order" => 0, "Status" => 1, "OwnerUins" => [$item['owner_uin']]
                ]);
                if(!empty($res['data']['AgentPayDealSet'])) {
                    $item['total_price'] = 0;
                    $lists = [];
                    $temp = array_column($res['data']['AgentPayDealSet'], "BigDealId", "DealName");
                    foreach ($res['data']['AgentPayDealSet'] as $it) {
                        if (isset($temp[$item['deal_name']]) && $it["BigDealId"] == $temp[$item['deal_name']]) {
                            $item['total_price'] += $it["GoodsPrice"]['RealTotalCost'] / 100;
                            $lists[] = $it["DealName"];
                        }
                    }
                }
                if($this->AU['position'] != "超级管理员"){
                    $res = TcScfUtil::getInstance($con->tencent_secretid, $con->tencent_secrekey, 'partner')->describeAgentAuditedClients([
                        "ClientUin" => $item['owner_uin']
                    ]);
                    $ClientType = !empty($res["data"]['AgentClientSet']) ? $res["data"]['AgentClientSet'][0]['ClientType'] : "";
                    if($ClientType == "new") {
                        if ($item['total_price'] > $user_discount['quota']) {
                            return $this->return_result(ErrorCode::code("customized", "订单金额大于代付限额"));
                        }
                    }elseif($ClientType == 'old'){
                        if ($item['total_price'] > $user_discount['old_quota']) {
                            return $this->return_result(ErrorCode::code("customized", "订单金额大于代付限额"));
                        }
                    }elseif($ClientType == 'assign'){
                        if ($item['total_price'] > $user_discount['assign_quota']) {
                            return $this->return_result(ErrorCode::code("customized", "订单金额大于代付限额"));
                        }
                    }else{
                        return $this->return_result(ErrorCode::code("customized", "客户类型错误"));
                    }
                }
                //添加本地订单
                $order["order_sn"] = date("YmdHis") . rand(100, 999).$k;
                $order["title"] = "腾讯云订单";
                $order["type"] = 1;
                $order["uid"] = $this->AU['id'];
                $order["uname"] = $this->AU['name'];
                $order["price"] = $item['total_price'];  //单价
                $order["amount"] = $item['total_price'] ;
                $order["submitter"] = $this->AU['name'];
                $order["total_price"] = $item['total_price'];
                $order["discount"] = '';
                $order["long"] = 4;
                $order["pay_status"] = 2;
                $order["status"] = 1;
                $order["pay_type"] = 2;
                $order["owner_uin"] = $item['owner_uin'];
                $order["pay_time"] = Carbon::now()->toDateTimeString();
                $order["created_at"] = Carbon::now()->toDateTimeString();
                $order["updated_at"] = Carbon::now()->toDateTimeString();
                Orders::query()->insertGetId($order);
                //添加消费记录
                $log["uid"] = $this->AU['id'];
                $log["type"] = 9;
                $log["money"] = '-' . $item['total_price'];
                $log["wallet"] = '后台用户代付';
                $log["remarks"] = "腾讯云订单付款";
                $log["operation"] = "余额消费￥" . $item['total_price'] . ",订单号：" . $order["order_sn"];
                $log["created_at"] = Carbon::now()->toDateTimeString();
                $log["updated_at"] = Carbon::now()->toDateTimeString();
                WalletLogs::query()->insertGetId($log);
                $res = TcScfUtil::getInstance($con->tencent_secretid, $con->tencent_secrekey, 'partner')->agentPayDeals([
                    "OwnerUin" => $item['owner_uin'], "DealNames" => $lists, "AgentPay" => 1,//1：代付  0：自付
                ]);
                if($res["code"] != 0){
                    if(strpos($res["msg"], "DealNames is null or empty") !== false){
                        DB::rollback();
                        $res["msg"] = "此订单状态正在更新，请稍后";
                    }else {
                        throw new \Exception($res["msg"]);
                    }
                }
            }
            DB::commit();
        } catch(\Exception $e){
            DB::rollback();
            return $this->return_result(ErrorCode::code("customized", $e->getMessage()));
        }
        $this->returnData['msg'] = '支付成功';
        $this->returnData['data'] = '';
        return $this->return_result($this->returnData);
    }

    //查询代理商返佣信息
    public function agent_discount(Request $request){
        $con = Configs::query()->where("mall_id", $request->mallData["id"])->first();
        $cred = new Credential($con->tencent_secretid, $con->tencent_secrekey);
        $httpProfile = new HttpProfile();
        $httpProfile->setEndpoint("partners.tencentcloudapi.com");
        $clientProfile = new ClientProfile();
        $clientProfile->setHttpProfile($httpProfile);
        $client = new PartnersClient($cred, "", $clientProfile);

        $page_size = $request->input('page_size', 10);
        $page_no = $request->input('page_no', 1);
        $req = new DescribeRebateInfosRequest();
        $req->RebateMonth = "2018-12"; //返佣月份
        $req->Offset = $page_no -1;
        $req->Limit = $page_size;
        $resp = $client->DescribeRebateInfos($req);
        $res = $resp->toJsonString();
    }

    // 缓存查询客户订单
    public function select_customer_cache_orders(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $con = Configs::query()->where("mall_id", $request->mallData["id"])->first();
        if (!$con->tencent_secretid || !$con->tencent_secrekey){
            return ErrorCode::code("customized", "腾讯云参数未配置");
        }
        $start_time = $request->input('start_time');
        $end_time = $request->input('end_time');
        $requestParams = [
            'Offset' => $request->page_no ? $request->page_no - 1 : 0, 'Limit' => $request->page_size ?: 10, "Order" => 0
        ];
        $requestParams["Offset"] = $requestParams["Offset"] * $requestParams["Limit"];
        if($request->status){
            $requestParams['Status'] = intval($request->status);
        }
        if($request->owner_uin){
            $requestParams['OwnerUins'][0] = $request->owner_uin;
        }
        if($request->deal_names){
            $requestParams['DealNames'][0] = $request->deal_names;
        }
        if($start_time){
            $requestParams['CreatTimeRangeStart'] = $start_time;
        }
        if($end_time){
            $requestParams['CreatTimeRangeEnd'] = $end_time;
        }
        if($request->input('payerMode')){
            $requestParams['PayerMode'] = intval($request->input('payerMode'));
        }
        $res = TcScfUtil::getInstance($con->tencent_secretid, $con->tencent_secrekey, 'partner')->describeSalesmans(["Offset" => 0, "Limit" => 100000]);
        $salesData = !empty($res["data"]['AgentSalesmanSet']) ? $res["data"]['AgentSalesmanSet'] : [];
        $res = TcScfUtil::getInstance($con->tencent_secretid, $con->tencent_secrekey, 'partner')->describeAgentDealsCache($requestParams);
        if ($res['code'] == 0){
            $this->returnData['data'] = [
                "total" => $res['data']['TotalCount'], "count" => $res['data']['TotalCount'], "list" => UpTools::transferFields($res['data']['AgentDealSet'])
            ];
            $this->getOrder($this->returnData["data"], $request, $requestParams, $con);
            foreach ($this->returnData["data"]["list"] as &$item){
                $item["salesName"] = '';
                foreach ($salesData as $t){
                    if($t["SalesUin"] == $item["salesUin"]) {
                        $item["salesName"] = $t["SalesName"];
                        break;
                    }
                }
            }
            return $this->return_result($this->returnData);
        }else{
            $this->returnData['code'] = 1;
            $this->returnData['msg'] = isset($res['msg']) ? ($res['msg'] == 'CreatTimeRangeStart must be within 15 days' ? "搜索时间必须在15天内" : $res['msg']) : '请求失败';
            return $this->return_result($this->returnData);
        }
    }

    public function getOrder(&$data, $request, $requestParams, $con, $type = 1){
        if ($request->sales_uin) {
            $saleUin[] = $request->sales_uin;
        } else {
            if ($this->AU["position"] != "超级管理员") {
                $tt = DB::table('permissions as p')
                    ->leftJoin('admin_permission_role as pr', 'pr.permission_id', '=', 'p.id')
                    ->leftJoin('admin_role_user as ru', 'ru.role_id', '=', 'pr.role_id')
                    ->where("ru.user_id", $this->AU["id"])
                    ->where("p.name", "admin.tencent.checkAllOrder")
                    ->count();
                if ($tt) {
                    return true;
                }
            }else{
                return true;
            }
            $sdf = TcAuther::query()->where(["mall_id" => $request->mallData["id"], "admin_id" => $this->AU["id"]])->select("id")->with("sale_list")->first();
            if (!empty($sdf["sale_list"])) {
                $saleUin = array_column($sdf["sale_list"]->toArray(), "sales_uin");
            }
        }
        if (!empty($saleUin)) {
            global $num;
            $num = 0;
            $fun = function ($data, $totalLimit, $start) use ($saleUin) {
                global $num;
                $temp = [];
                foreach ((array)$data as $item) {
                    if (in_array($item["salesUin"], $saleUin) || (!$item["salesUin"] && in_array($this->defaultSale[0]["sales_uin"], $saleUin))) {
                        if ($totalLimit > $num && $start <= $num) {
                            $temp[] = $item;
                            $num++;
                        } else {
                            break;
                        }
                    }
                }
                return $temp;
            };
            $pageNo = $request->page_no ?: 1;
            if ($pageNo > 1) {
                $tempParam = $requestParams;
                $total = $tempParam["Limit"] * ($pageNo - 1);
                $tempData = [];
                for ($i = 1; $i <= ceil($total / 1000); $i++) {
                    $tempParam["Offset"] = ($i - 1) * 1000;
                    $tempParam["Limit"] = $total <= 1000 * $i ? $total - $tempParam["Offset"] : 1000;
                    if ($type === 1) {
                        $res = TcScfUtil::getInstance($con->tencent_secretid, $con->tencent_secrekey, 'partner')->describeAgentDealsCache($tempParam);
                        if (!empty($res['data']['AgentDealSet'])) {
                            $tempData = array_merge($tempData, UpTools::transferFields($res['data']['AgentDealSet']));
                        }
                    } else {
                        $res = TcScfUtil::getInstance($con->tencent_secretid, $con->tencent_secrekey, 'partner')->describeAgentPayDeals($tempParam);
                        if (!empty($res['data']['AgentPayDealSet'])) {
                            $tempData = array_merge($tempData, UpTools::transferFields($res['data']['AgentPayDealSet']));
                        }
                    }
                }
                $data["list"] = array_merge($tempData, $data["list"]);
                unset($tempData);
            }
            $totalLimit = $requestParams["Limit"];
            $data["list"] = $fun($data["list"], $totalLimit, $requestParams["Offset"]);
            $data["count"] = count($data["list"]);
            while ($totalLimit > $num) {
                if ($data["total"] <= $requestParams["Offset"]) {
                    break;
                }
                $requestParams["Offset"] = $requestParams["Offset"] + $requestParams["Limit"];
                $requestParams["Limit"] = 1000;
                if ($type === 1) {
                    $res = TcScfUtil::getInstance($con->tencent_secretid, $con->tencent_secrekey, 'partner')->describeAgentDealsCache($requestParams);
                    if (!empty($res['data']['AgentDealSet'])) {
                        $res = $fun(UpTools::transferFields($res['data']['AgentDealSet']), $totalLimit, 0);
                        $data["list"] = array_merge($data["list"], $res);
                        $data["count"] = count($data["list"]);
                    }
                } else {
                    $res = TcScfUtil::getInstance($con->tencent_secretid, $con->tencent_secrekey, 'partner')->describeAgentPayDeals($requestParams);
                    if (!empty($res['data']['AgentPayDealSet'])) {
                        $res = $fun(UpTools::transferFields($res['data']['AgentPayDealSet']), $totalLimit, 0);
                        $data["list"] = array_merge($data["list"], $res);
                        $data["count"] = count($data["list"]);
                    }
                }
            }
        } else {
            $data["count"] = 0;
            $data["list"] = [];
        }
    }

    public function getInviteInfo(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $con = Configs::query()->where("mall_id", $request->mallData["id"])->first();
        $this->returnData["data"] = [
            "tencent_invite_url" => $con->tencent_invite_url,
            "tencent_big_qr" => $this->processingPictures($con->tencent_big_qr),
            "tencent_small_qr" => $this->processingPictures($con->tencent_small_qr),
            "invite_url" => TcAuther::query()->where(["admin_id" => $this->AU["id"], "mall_id" => $request->mallData["id"]])->value("invite_url")
        ];
        return $this->return_result($this->returnData);
    }

    // 实时查询客户订单
    public function select_customer_orders(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $con = Configs::query()->where("mall_id", $request->mallData["id"])->first();
        if (!$con->tencent_secretid || !$con->tencent_secrekey){
            return ErrorCode::code("customized", "腾讯云参数未配置");
        }
        $start_time = $request->input('start_time');
        $end_time = $request->input('end_time');
        $requestParams = [
            'Offset' => $request->page_no ? $request->page_no - 1 : 0,  'Limit' => $request->page_size ?: 10, "Order" => 0
        ];
        $requestParams["Offset"] = $requestParams["Offset"] * $requestParams["Limit"];
        if($request->status){
            $requestParams['Status'] = intval($request->status);
        }
        if($request->owner_uin){
            $requestParams['OwnerUins'][0] = $request->owner_uin;
        }
        if($request->deal_names){
            $requestParams['DealNames'][0] = $request->deal_names;
        }
        if($start_time){
            $requestParams['CreatTimeRangeStart'] = $start_time;
        }
        if($end_time){
            $requestParams['CreatTimeRangeEnd'] = $end_time;
        }
        $res = TcScfUtil::getInstance($con->tencent_secretid, $con->tencent_secrekey, 'partner')->describeSalesmans(["Offset" => 0, "Limit" => 100000]);
        $salesData = !empty($res["data"]['AgentSalesmanSet']) ? $res["data"]['AgentSalesmanSet'] : [];
        $res = TcScfUtil::getInstance($con->tencent_secretid, $con->tencent_secrekey, 'partner')->describeAgentPayDeals($requestParams);
        if ($res['code'] == 0){
            $this->returnData['data'] = ["total" => $res['data']['TotalCount'], "list" => UpTools::transferFields($res['data']['AgentPayDealSet'])];
            $this->getOrder($this->returnData["data"], $request, $requestParams, $con, 2);
              foreach ($this->returnData["data"]["list"] as &$item){
                  $item["salesName"] = '';
                  foreach ($salesData as $t){
                      if($t["SalesUin"] == $item["salesUin"]) {
                          $item["salesName"] = $t["SalesName"];
                          break;
                      }
                  }
              }
            return $this->return_result($this->returnData);
        }else{
            $this->returnData['code'] = 1;
            $this->returnData['msg'] = isset($res['msg']) ? ($res['msg'] == 'CreatTimeRangeStart must be within 15 days' ? "搜索时间必须在15天内" : $res['msg']) : '请求失败';
            return $this->return_result($this->returnData);
        }
    }

    // 获取代付用户列表
    public function getAdminData(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $page = $request->page_no ?: 1;
        $pageSize = $request->page_size ?: 10;
        $db = TcAuther::query()->from(TcAuther::query()->getModel()->getTable()." as t")
            ->with("sale_list")
            ->leftJoin(AdminUser::query()->getModel()->getTable()." as u", "t.admin_id", "=", "u.id")
            ->where(["t.mall_id" => $request->mallData["id"]])
            ->select("t.*", "u.name", "u.mobile", "u.wechat_id");
        if($request->searchValue){
            $db->where("u.name", "like", "%{$request->searchValue}%");
        }
        $data = $db->skip(($page - 1) * $pageSize)->take($pageSize)->get()->toArray();
        $this->returnData["data"] = ["total" => $db->count(), "rows" => $data];
        return $this->return_result($this->returnData);
    }

    public function addAdmin(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        if(!$request->admin_id){
            return $this->return_result(ErrorCode::code("params_not_exist", "系统用户Id"));
        }
        if(!$request->sale_list){
            return $this->return_result(ErrorCode::code("params_not_exist", "业务员列表"));
        }
        $data = ["admin_id" => $request->admin_id, "create_time" => Carbon::now()->toDateTimeString(), "mall_id" => $request->mallData["id"]];
        $data['quota'] = $request->quota ?: 0;
        $data['old_quota'] = $request->old_quota ?: 0;
        $data['assign_quota'] = $request->assign_quota ?: 0;
        $data['transfer_quota'] = $request->transfer_quota ?: 0;
        $data['invite_url'] = $request->invite_url ?: "";
        if($id = TcAuther::query()->insertGetId($data)){
            $saleList = @json_decode($request->sale_list, true);
            foreach ($saleList as $item){
                if(isset($item["SalesUin"]) && isset($item["SalesName"])){
                    TcSale::query()->insert([
                        "relate_id" => $id, "sales_name" => $item["SalesName"], "sales_uin" => $item["SalesUin"],
                        "create_time" => Carbon::now()->toDateTimeString()
                    ]);
                }
            }
        }else{
            return $this->return_result(ErrorCode::code("customized", "添加失败"));
        }
        return $this->return_result($this->returnData);
    }

    public function updateAdmin(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        if(!$request->id){
            return $this->return_result(ErrorCode::code("params_not_exist", "id"));
        }
        if(!$request->sale_list){
            return $this->return_result(ErrorCode::code("params_not_exist", "业务员列表"));
        }
        $data['quota'] = $request->input('quota', 0);
        $data['old_quota'] = $request->input('old_quota', 0);
        $data['assign_quota'] = $request->input('assign_quota', 0);
        $data['transfer_quota'] = $request->input('transfer_quota', 0);
        $data['invite_url'] = $request->input('invite_url', "");
        $data['update_time'] = Carbon::now()->toDateTimeString();
        $res = TcAuther::query()->where(["id" => $request->id])->update($data);
        if($res || $res === 0){
            $saleList = @json_decode($request->sale_list, true);
            foreach ($saleList as $item){
                if(isset($item["SalesUin"]) && isset($item["SalesName"])){
                    if(!TcSale::query()->where(["relate_id" => $request->id, "sales_uin" => $item["SalesUin"]])->count()) {
                        TcSale::query()->insert([
                            "relate_id" => $request->id, "sales_name" => $item["SalesName"], "sales_uin" => $item["SalesUin"],
                            "create_time" => Carbon::now()->toDateTimeString()
                        ]);
                    }
                }
            }
            TcSale::query()->where(["relate_id" => $request->id])->whereNotIn("sales_uin", array_column($saleList, "SalesUin"))->delete();
        }else{
            return $this->return_result(ErrorCode::code("customized", "更新失败"));
        }
        return $this->return_result($this->returnData);
    }

    public function delAdmin(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        if(!$request->id){
            return $this->return_result(ErrorCode::code("params_not_exist", "id"));
        }
        TcAuther::query()->where("id", $request->id)->delete();
        TcSale::query()->where("relate_id", $request->id)->delete();
        return $this->return_result($this->returnData);
    }

    //作用：格式化参数，签名过程需要使用
    public function formatBizQueryParaMap($paraMap, $urlencode)
    {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v) {
            if ($urlencode) {
                $v = urlencode($v);
            }
            $buff .= $k . "=" . $v . "&";
        }
        $reqPar = '';
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff) - 1);
        }
        return $reqPar;
    }


    //获取腾讯云配置
    public function tencent_config(){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $configModel = new Configs();
        $res = $configModel->getConfigByID();
        $data['code'] = 0;
        $data['msg'] = '请求成功';
        $data["data"]["tencent"]['tencent_id'] = $this->Codereplace($res['tencent_id'],4);
        $data["data"]["tencent"]['tencent_appid'] = $this->Codereplace($res['tencent_appid'],4);
        $data["data"]["tencent"]['tencent_secretid'] = $this->Codereplace($res['tencent_secretid'],8);
        $data["data"]["tencent"]['tencent_secrekey'] = $this->Codereplace($res['tencent_secrekey'],8);
        $data["data"]["tencent"]['tencent_invite_url'] = $res["tencent_invite_url"];
        $data["data"]["tencent"]['tencent_big_qr'] = $this->processingPictures($res["tencent_big_qr"]);
        $data["data"]["tencent"]['tencent_small_qr'] = $this->processingPictures($res["tencent_small_qr"]);

        $data["data"]["agent"]['tencent_pay_status'] = $res["tencent_pay_status"];
        $data["data"]["agent"]['tencent_pay_quota'] = $res["tencent_pay_quota"];
        $data["data"]["agent"]['tencent_pay_discount'] = $res["tencent_pay_discount"];
        $data["data"]["agent"]['tencent_not_discount'] = $res["tencent_not_discount"] ? (array)@explode(",", $res["tencent_not_discount"]) : array();
        return $this->return_result($data);
    }

    //字符串打码
    private function Codereplace($string,$length){
        $len = strlen($string);//10
        $start = $length/2;
        $replace_len = $len - $length;//6
        $code = '';
        for ($i=0;$i<$replace_len;$i++) {         //通过循环指定长度
            $code .= "*";
        }
        $new_string = substr_replace($string,$code,$start,$replace_len);
        return $new_string;
    }


    //修改腾讯云配置
    public function update_tencent_config(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $type = $request->type ?: "tencent";
        if($type == "tencent") {
            $tencent_id = $request->input('tencent_id', '*');                //腾讯云id
            $tencent_appid = $request->input('tencent_appid', '*');          //腾讯云APPid
            $tencent_secretid = $request->input('tencent_secretid', '*');   //腾讯云secretid
            $tencent_secrekey = $request->input('tencent_secrekey', '*');   //腾讯云secrekey
            //验证参数
            $data = [];
            $info_1 = strpbrk($tencent_id, "*");
            if (!$info_1) {
                $data['tencent_id'] = $tencent_id;
            }
            $info_2 = strpbrk($tencent_appid, "*");
            if (!$info_2) {
                $data['tencent_appid'] = $tencent_appid;
            }
            $info_3 = strpbrk($tencent_secretid, "*");
            if (!$info_3) {
                $data['tencent_secretid'] = $tencent_secretid;
            }
            $info_4 = strpbrk($tencent_secrekey, "*");
            if (!$info_4) {
                $data['tencent_secrekey'] = $tencent_secrekey;
            }
            if ($request->tencent_invite_url) {
                $data["tencent_invite_url"] = $request->tencent_invite_url;
            }
            if ($request->tencent_big_qr) {
                $data["tencent_big_qr"] = $request->tencent_big_qr;
            }
        }else {
            if (isset($request->tencent_pay_status) && $request->tencent_pay_status != '') {
                $data["tencent_pay_status"] = $request->tencent_pay_status;
            }
            if (isset($request->tencent_pay_quota) && $request->tencent_pay_quota != '') {
                $data["tencent_pay_quota"] = $request->tencent_pay_quota;
            }
            if (isset($request->tencent_pay_discount) && $request->tencent_pay_discount != '') {
                $data["tencent_pay_discount"] = $request->tencent_pay_discount;
            }
            if ($request->tencent_not_discount) {
                $data["tencent_not_discount"] = $request->tencent_not_discount;
            }
        }
        if (empty($data)){
            $this->returnData['msg'] = "未做修改，更新失败";
            return $this->return_result($this->returnData);
        }
        $configModel = new Configs();
        $res = $configModel->configUpdate($data);
        if(!$res){
            $this->returnData = ErrorCode::$admin_enum['not_exist'];
            $this->returnData['msg'] = '更新失败';
            return $this->return_result($this->returnData);
        }
        $this->returnData['msg'] = "更新成功";
        return $this->return_result($this->returnData);
    }

    //获取数据库保存的订单
    public function get_tencent_orders(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $dealName = $request->input('deal_name','');
        $status = $request->input('status','');
        $page_no = $request->input('page_no',1);
        $page_size = $request->input('page_size',20);

        $res = DB::table('tencent_order')->select();
        $res_price = DB::table('tencent_order_price')->get();
        $res_price = json_decode(json_encode($res_price),true);
        if($dealName){
            $res->where('dealName',$dealName);
        }
        if($status){
            $res->where('status',$status);
        }
        $start = ($page_no-1) * $page_size;
        $total = $res;
        $data['total'] = $total->count();
        $data['list'] = $res->skip($start)->take($page_size)->get();
        $data['list'] = json_decode(json_encode($data['list']),true);
        foreach ($data['list'] as $k=>&$v){
                $v['goodsPrice'] = $res_price[$v['id']-1];
        }
        $result['code'] = 0;
        $result['msg'] = '请求成功';
        $result['data'] = $data;
        return $this->return_result($result);
    }

    //修改客户腾讯云代付折扣
    public function update_discount(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $data['tencent_discount'] = $request->input('tencent_discount', 0);
        $data['quota'] = $request->input('quota', 0);
        $data['tencent_old_discount'] = $request->input('tencent_old_discount', 0);
        $data['old_quota'] = $request->input('old_quota', 0);
        $data['tencent_assign_discount'] = $request->input('tencent_assign_discount', 0);
        $data['assign_quota'] = $request->input('assign_quota', 0);
        $id = $request->input('id');
        $memberModel = new MemberBase();
        $res = $memberModel->memberUpdate($id,$data);
        if ($res){
            return $this->return_result($this->returnData);
        }else{
            $this->returnData['code'] = 1;
            $this->returnData['msg'] = '请求失败';
            return $this->return_result($this->returnData);
        }
    }

    //修改客户代付权限
    public function tencent_status(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $data['tencent_status'] = $request->input('status');
        $id = $request->input('id');
        $memberModel = new MemberBase();
        $res = $memberModel->memberUpdate($id,$data);
        if ($res){
            return $this->return_result($this->returnData);
        }else{
            $this->returnData['code'] = 1;
            $this->returnData['msg'] = '请求失败';
            return $this->return_result($this->returnData);
        }
    }

    // 下载数据分析
    public function downDataAnalysis(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        if(!$request->startTime || !$request->endTime){
            return $this->return_result(ErrorCode::code("customized", "时间错误"));
        }
        $data = [
            "mall_id" => $request->mallData["id"], "status" => 1, "user_id" => $this->AU["id"],
            "start_time" => date("Y-m-d 00:00:00", strtotime($request->startTime)),
            "end_time" => date("Y-m-d 23:59:59", strtotime($request->endTime)),
            "create_time" => Carbon::now()->toDateTimeString(),
            "down_time" => Carbon::now()->toDateTimeString(),
            "generate_time" => Carbon::now()->toDateTimeString()
        ];
        $data["name"] = "客户订单-{$data["start_time"]}-{$data["end_time"]}-".time().".csv";
        $id = TencentTemp::query()->insertGetId($data);
        global $scf_data;
        if(empty($scf_data['IS_SCF'])){ // 服务器版，就把任务交给swoole处理了
            $client = new \swoole_client(SWOOLE_SOCK_TCP);
            if (!$client->connect("127.0.0.1", 9501, 1)) {
                throw new \Exception(sprintf('Swoole Error: %s', $client->errCode));
            }
            if ($client->isConnected()) {
                $client->send(json_encode(["id" => $id, "type" => "tencentDataAnalysis"]));
            } else {
                throw new \Exception('Swoole Server does not connected.');
            }
            $client->close();
        }
        return $this->return_result($this->returnData);
    }

    public function getAnalysisList(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $pageNo = $request->page ?: 1;
        $pageSize = $request->page_size ?: 10;
        $db = TencentTemp::query()->with(["user" => function($query){
            $query->select("id", "name");
        }])->where(["mall_id" => $request->mallData["id"], "user_id" => $this->AU["id"]]);
        $data['total'] = $db->count();
        $data['rows'] = $db->skip(($pageNo-1) * $pageSize)->take($pageSize)->orderBy("id", "desc")->get()->toArray();
        foreach ($data["rows"] as &$item){
            $item["userName"] = !empty($item["user"]["name"]) ? $item["user"]["name"] : "";
            $item["type"] = $item["type"] == "1" ? "客户订单" : "";
            unset($item["user"]);
            if($item["address"] && strpos($item["address"], "http") === false){
                $item["address"] = CommonServer::getUrl($item["address"]);
            }
        }
        unset($item);
        $this->returnData["data"] = $data;
        return $this->return_result($this->returnData);
    }

    public function updateTime(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        if(!$request->id){
            return $this->return_result(ErrorCode::code("params_not_exist", "id"));
        }
        $data = TencentTemp::query()->where("id", "=", $request->id)->first();
        if(empty($data)){
            return $this->return_result(ErrorCode::code("customized", "数据不存在"));
        }
        $data->down_time = Carbon::now()->toDateTimeString();
        $data->save();
        return $this->return_result($this->returnData);
    }

    public function getAnalysisData(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        if(!$request->id){
            return $this->return_result(ErrorCode::code("params_not_exist", "id"));
        }
        $database = TencentTemp::query()->where("id", "=", $request->id)->first();
        if(empty($database)){
            return $this->return_result(ErrorCode::code("customized", "数据不存在"));
        }
        $con = Configs::query()->where("mall_id", $request->mallData["id"])->first();
        if (!$con->tencent_secretid || !$con->tencent_secrekey){
            return ErrorCode::code("customized", "腾讯云参数未配置");
        }
        $pageNo = $request->page ?: 1;
        $pageSize = $request->page_size ?: 10;
        $where = ["mall_id" => $request->mallData["id"]];
        if($request->status){
            $where['status'] = intval($request->status);
        }
        if($request->owner_uin){
            $where['owner_uin'] = $request->owner_uin;
        }
        if($request->deal_names){
            $where['deal_name'] = $request->deal_names;
        }
        if($request->payerMode != ""){
            $where['payer_mode'] = intval($request->payerMode);
        }
        if($request->sales_uin){
            $where['sales_uin'] = $request->sales_uin;
        }
        if($request->sales_uin){
            $where['sales_uin'] = $request->sales_uin;
        }
        if($request->client_remark){
            $where['client_remark'] = $request->client_remark;
        }
        $db = TencentOrder::query()
            ->where($where)->whereBetween("creat_time", [$database->start_time, $database->end_time]);
        if ($this->AU["position"] != "超级管理员") {
            $tt = DB::table('permissions as p')
                ->leftJoin('admin_permission_role as pr', 'pr.permission_id', '=', 'p.id')
                ->leftJoin('admin_role_user as ru', 'ru.role_id', '=', 'pr.role_id')
                ->where("ru.user_id", $this->AU["id"])
                ->where("p.name", "admin.tencent.checkAllOrder")
                ->count();
            if (!$tt) {
                $sdf = TcAuther::query()->where(["mall_id" => $request->mallData["id"], "admin_id" => $this->AU["id"]])->select("id")->with("sale_list")->first();
                $saleUin = !empty($sdf["sale_list"]) ? array_column($sdf["sale_list"]->toArray(), "sales_uin") : [];
                $db->whereIn("sales_uin", $saleUin);
            }
        }
        $data['total'] = $db->count();
        $agentData = [];
        $data['rows'] = $db->skip(($pageNo-1) * $pageSize)->take($pageSize)->orderBy("creat_time", "asc")->get()->toArray();
        foreach ($data["rows"] as &$item){
            if(!isset($agentData[$item["sales_uin"]])) {
                $res = TcScfUtil::getInstance($con->tencent_secretid, $con->tencent_secrekey, 'partner')
                    ->describeSalesmans(["Offset" => 0, "Limit" => 1, "SalesUin" => $item["sales_uin"]]);
                $agentData[$item["sales_uin"]] = !empty($res["data"]['AgentSalesmanSet']) ? $res["data"]['AgentSalesmanSet'][0]["SalesName"] : "";
            }
            $item["sales_name"] = $agentData[$item["sales_uin"]];
            $item["payer_mode"] = strval($item["payer_mode"]);
        }
        $data["date"] = date("Y-m-d", strtotime($database->start_time))." - ".date("Y-m-d", strtotime($database->end_time));
        $this->returnData["data"] = $data;
        return $this->return_result($this->returnData);
    }

    public function getAnalysisStatistics(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        if(!$request->id){
            return $this->return_result(ErrorCode::code("params_not_exist", "id"));
        }
        $type = $request->type && in_array($request->type, ["purchase", 'renew', 'modify']) ? $request->type : "all";
        $salesUni = $request->sales_uin ?: "";
        $field = [
            "s.sales_money", "s.sales_list", 's.owner_uin_money', 's.product_money',
            "t.start_time", "t.end_time"
        ];
        if($salesUni){
            $field = array_merge($field, ["s.sales_data"]);
        }else{
            $field = array_merge($field, ["s.{$type}", "s.money", "s.achieve"]);
        }
        $database = TencentTemp::query()->from(TencentTemp::query()->getModel()->getTable()." as t")
            ->leftJoin(TencentStatistics::query()->getModel()->getTable()." as s", "s.relate_id", "=", "t.id")
            ->where(["t.mall_id" => request()->mallData["id"], "t.id" => $request->id])
            ->select($field)
            ->first();
        $data = $sales_list = $statistics = $date = [];
        $money = $achieve = 0;
        if(!empty($database)){
            $sales_list = (array)@json_decode($database->sales_list, true);
            if($salesUni){
                $salesData = (array)@json_decode($database->sales_data, true);
                $data = $salesData[$salesUni][$type] ?? [];
                $achieve = $salesData[$salesUni]["achieve"] ?? 0;
                $money = $salesData[$salesUni]["money"] ?? 0;
            }else{
                $data = (array)@json_decode($database->$type, true);
                $achieve = $database->achieve ?: 0;
                $money = $database->money ?: 0;
            }
            $statistics = [
                "sales_money" => (array)@json_decode($database->sales_money, true),
                "owner_uin_money" => (array)@json_decode($database->owner_uin_money, true),
                "product_money" => (array)@json_decode($database->product_money, true),
            ];
            $date = ["start" => $database->start_time, "end" => $database->end_time];
        }
        foreach ($data as &$item) {
            array_walk($item, function (&$value) {
                if (is_numeric($value)) {
                    $value = floatval($value);
                }
            });
        }
        unset($item);
        $this->returnData["data"] = [
            "sales_list" => $sales_list,
            "date" => $date,
            "list" => $data,
            "achieve" => $achieve,
            "money" => $money,
            "statistics" => $statistics,
            "type" => ["all" => "全部", "purchase" => "新购", "renew" => "续费", "modify" => "配置变更"]
        ];
        return $this->return_result($this->returnData);
    }

    public function getAgentBills(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        if(!$request->settle_month){
            return $this->return_result(ErrorCode::code("params_not_exist", "支付月份"));
        }
        $con = Configs::query()->where("mall_id", $request->mallData["id"])->first();
        if (!$con->tencent_secretid || !$con->tencent_secrekey){
            return ErrorCode::code("customized", "腾讯云参数未配置");
        }
        $requestParam = [
            "SettleMonth" => $request->settle_month, "Offset" => $request->page_no ?: 1, "Limit" => $request->page_size ?: 20
        ];
        $requestParam["Offset"] = ($requestParam["Offset"] - 1) * $requestParam["Limit"];
        if($request->client_uin){
            $requestParam["ClientUin"] = strval($request->client_uin);
        }
        if($request->pay_mode){
            $requestParam["PayMode"] = $request->pay_mode;
        }
        if($request->order_id){
            $requestParam["OrderId"] = strval($request->order_id);
        }
        if($request->client_remark){
            $requestParam["ClientRemark"] = $request->client_remark;
        }
        $res = TcScfUtil::getInstance($con->tencent_secretid, $con->tencent_secrekey, 'partner')->describeAgentBills($requestParam);
        if ($res["code"] != 0){
            $this->returnData = $res;
        }else{
            $res['data']['AgentBillSet'] = UpTools::transferFields($res['data']['AgentBillSet']);
            $money = 0;
            $data = [];
            foreach ($res['data']['AgentBillSet'] as $item){
                if($request->client_type && $request->payer_mode){
                    if($item["clientType"] == $request->client_type && $item["payerMode"] == $request->payer_mode) {
                        $data[] = $item;
                        $money += $item["amt"] / 100;
                        continue;
                    }
                }else {
                    if(!$request->payer_mode && !$request->client_type) {
                        $data[] = $item;
                        $money += $item["amt"] / 100;
                        continue;
                    }else {
                        if ($request->payer_mode && $item["payerMode"] == $request->payer_mode) {
                            $data[] = $item;
                            $money += $item["amt"] / 100;
                            continue;
                        }
                        if ($request->client_type && $item["clientType"] == $request->client_type) {
                            $data[] = $item;
                            $money += $item["amt"] / 100;
                            continue;
                        }
                    }
                }
            }
            $this->returnData['data'] = [
                "list" => $data,
                "total" => $res['data']['TotalCount'],
                "money" => sprintf("%.2f", $money)
            ];
        }
        return $this->return_result($this->returnData);
    }
}

